﻿using MvcPaging;
using Ninject;
using Peninsula.DataAccess.POCO;
using Peninsula.Site.Data.Result;
using Peninsula.Utility.Extensions;
using Peninsula.Utility.Helper;
using Peninsula.Web.Areas.Backstage.Models.Households;
using Peninsula.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Peninsula.Web.Areas.Backstage.Controllers
{
    public class HouseholdsController :AdminBaseController
    {
        [Inject]
        public IServices.IHouseholdsRestatisticsService HouseholdsRestatisticsService { get; set; }

        static string roleName = RoleEnum.Households.EnumDescription();
        /// <summary>
        /// 查询户主
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        // GET: Backstage/Households
        public ActionResult Index(HouseholdsPagedListModel viewModel)
        {
            SetPageTitle("户主");
            viewModel.PagedList = Householdsmanger.All()
                .Where(h => h.UserName.ContainsNoCase(viewModel.Keyword)
                ||h.TrueName.ContainsNoCase(viewModel.Keyword)||h.Phone==viewModel.Keyword
                ||h.Email==viewModel.Keyword||h.Numbering.ToString()==viewModel.Keyword
                ).OrderByDescending(s=>s.CreatedTime)
                .ToPagedList(viewModel.PageIndex, viewModel.Size);

            viewModel.QueryParameter = GetParameterFromQueryString();
            return View(viewModel);
        }

       /// <summary>
       /// 新增或编辑住户                
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        [HttpGet]
        public ActionResult CreateOrEditHouseholds(string id) {
            Households households = null;
            if (id.IsNotNullAndNotWhiteSpace())
            {
                households = Householdsmanger.Get(h => h.Id == id);
                if (households.IsNull())
                {
                    return RedirectToError("没找到对应的户主", code: 404);
                }
                ViewBag.IsEdit = true;
            }
            else
            {
                households = new Households();
                ViewBag.IsEdit = false;
            }
            ViewBag.AllRoles = RoleManager.RoleProvider.Entities.Where(r => r.RoleName == roleName);
            SetPageTitle(ViewBag.IsEdit ? "编辑户主" : "创建户主");
            return View(households);
        }
        /// <summary>
        /// 新增或编辑户主
        /// </summary>
        /// <param name="isEdit"></param>
        /// <param name="postHouseholds"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditHouseholds(bool isEdit, DataAccess.POCO.Households postHouseholds) {
            var result = new JsonResultData();
            result.RunWithTry(item=> {
                if (isEdit)
                {
                    ModelState.Remove("Password");
                }
                if (ModelState.IsValid)
                {
                    if (isEdit)
                    {
                        var HouseholdsEntiy = Householdsmanger.Get(h => h.Id == postHouseholds.Id);
                        ValueCopyHelper.CopyProperty(HouseholdsEntiy,postHouseholds,false,
                            nameof(postHouseholds.TrueName),
                            nameof(postHouseholds.TrueName),
                            nameof(postHouseholds.Email),
                            nameof(postHouseholds.Phone),
                            nameof(postHouseholds.Sex),
                            nameof(postHouseholds.BuldiingsNum),
                            nameof(postHouseholds.LayersNum),
                            nameof(postHouseholds.Numbering),
                            nameof(postHouseholds.IsLockedOut)
                            );
                        HouseholdsEntiy.SetUpdateInfo(AdminSession.AdminEntity.UserName);
                        Householdsmanger.Update(HouseholdsEntiy);
                    }
                    else
                    {
                        var isExit = Householdsmanger.IsExitHouseHoldsUserName(postHouseholds.UserName);
                        if (!isExit)
                        {
                            isExit= Householdsmanger.IsExistHouseholds(postHouseholds.BuldiingsNum,
                            postHouseholds.LayersNum, postHouseholds.Numbering);
                            if (isExit)
                            {
                                result.Success = false;
                                result.AddMessage("已存在该门牌号住户，请仔细查看楼号，楼层数，门牌号！");
                                return;
                            }
                            postHouseholds.SetCreateAndUpdateInfo(AdminSession.AdminEntity.UserName);
                            Householdsmanger.Add(postHouseholds);
                       
                        }
                        else
                        {
                            result.Success = false;
                            result.AddMessage("用户名已存在！");
                            return;
                        }
                     
                    }
                    result.Success = true;
                    result.AddMessage("保存成功！");
                    result.RedirectUrl = Url.Action("Index");
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }              
            });
            return Json(result);
        }

        /// <summary>
        /// 删除户主
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id) {
            var result = new JsonResultData();
            result.RunWithTry(data=> {
                Householdsmanger.Delete(h => h.Id == id);
                data.Success = true;
                data.ReloadPage = true;
                data.AddMessage("删除成功！");
            });
            return JsonAllowGet(result);
        }
    }
}